package com.ljx.video.oss;

import com.ljx.video.domain.entity.File;
import com.ljx.video.domain.vo.req.FileUploadReq;
import com.ljx.video.mapper.VideoMapper;
import com.ljx.video.util.MinioUtil;
import io.minio.ComposeSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2025-02-02  19:16
 */
@Service
public class MinioStrategy implements OssStrategy {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private VideoMapper videoMapper;

    @Override
    public void upload(FileUploadReq req) {
        minioUtil.uploadChunkToMinio(req);
    }

    @Override
    public InputStream download(Long id, String tsNum) {
        File file = videoMapper.selectById(id);
        return minioUtil.getVideoStream(file.getFileMd5(), file.getFilename());
    }

    @Override
    public void merge(FileUploadReq req) {
        List<ComposeSource> composeSourceList = new ArrayList<>();
        for(int i = 0; i < req.getTotalChunk(); i++){
            composeSourceList.add(minioUtil.getComposeSourceByChunk(req.getFileMd5(), Long.parseLong(String.valueOf(i))));
        }
        minioUtil.mergeComposeSource(req.getFilename(), req.getFileMd5(), composeSourceList);
        minioUtil.clearChunks(req.getTotalChunk(), req.getFileMd5());
    }
}
